package com.weilx959.spt.plugin.e2sp.utils.sql.parser;

import com.weilx959.spt.plugin.e2sp.constant.ExcelToSqlConstants;
import com.weilx959.spt.plugin.e2sp.model.statement.CheckStatement;
import com.weilx959.spt.plugin.e2sp.model.statement.Statement;
import com.weilx959.spt.plugin.e2sp.utils.StringUtil;
import com.weilx959.spt.plugin.e2sp.utils.sql.SqlUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.delete.Delete;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 检查SQL解析器
 *
 * @author weilx
 * @since 2024-05-02
 */
@Slf4j
public class CheckSQLParser implements SQLParser {
    @Override
    public String parse(Statement statement) {
        CheckStatement checkStatement = SqlUtil.cast(statement, CheckStatement.class);
        String template = Optional.ofNullable(checkStatement.getTemplate()).orElse(ExcelToSqlConstants.DEFAULT_CHECK_SQL_TEMPLATE);
        Delete delete = checkStatement.getDeleteStatement().getDelete();
        String tableName = delete.getTable().toString();
        String whereCase = delete.getWhere().toString();

        Map<String, String> params = new HashMap<>();
        params.put("TABLE_NAME", tableName);
        params.put("TABLE_NAME_escape", "'" + SqlUtil.escape(tableName) + "'");
        params.put("WHERE_CASE", whereCase);
        params.put("WHERE_CASE_escape", "'" + SqlUtil.escape(whereCase) + "'");
        params.put("COUNT", String.valueOf(checkStatement.getInsertStatements().size()));
        log.debug("Check SQL template: {}, params: {}", template, params);
        return StringUtil.format(template, params);
    }
}
